package concurrencyPractice.chapter02;

import concurrencyPractice.GuardBy;
import concurrencyPractice.ThreadSafe;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.math.BigInteger;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序2-8 synchronized 适用于比较小的原子代码块
 * @date 2023/12/26 16:19:21
 */
@ThreadSafe
public class CachedFactorizer implements Servlet {
    @GuardBy("this")
    private BigInteger lastNumber;

    @GuardBy("this")
    private BigInteger[] lastFactors;

    @GuardBy("this")
    private long hits;

    @GuardBy("this")
    private long cacheHits;

    public synchronized long getHits() {
        return hits;
    }
    public synchronized double getCacheHitRadio () {
        return cacheHits/(double) hits;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        BigInteger i = extractFromRequest(servletRequest);
        BigInteger[] factors = null;

        synchronized (this) {
            ++ hits;
            if(i.equals(lastNumber)) {
                ++ cacheHits;
                factors = lastFactors.clone();
            }
        }

        if(factors == null) {
            factors = factor[i];

            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(servletResponse, factors);
    }


    private void encodeIntoResponse(ServletResponse resp, BigInteger[] factors) {
    }

    private BigInteger extractFromRequest(ServletRequest req) {
        return null;
    }
}
